//
//  HomeViewController.m
//  BP_NewClient
//
//  Created by  chentaoli on 15/4/8.
//  Copyright (c) 2015年 normal. All rights reserved.
//

#import "HomeViewController.h"
#import "BP_NewClient-Swift.h"
#import "BP_NewClient.pch"
#import "StoreListViewController.h"
#import "UIImageView+AFNetworking.h"
#import "ProductViewController.h"
#import "BPCategoryViewController.h"
#import "BPCityListViewController.h"
#import "HomeCell.h"
#import "CityModel.h"
#import "UIWebView+LoadProgress.h"
#import "BPBaseWebViewController.h"

@interface HomeViewController (){
    UINib           *nib;
    UIView          *headerBtnView;
    UIView          *headerBtnView1;
    NSArray         *titleArray0;
    NSArray         *titleArray1;
}

@end

@implementation HomeViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self hideTabbar:NO];
    [_bannerView startRolling];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [_bannerView stopRolling];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];    
}


-(void)EScrollerViewDidClicked:(NSUInteger)index
{
    NSLog(@"index--%lu",(unsigned long)index);
}

// 登录
- (IBAction)loginIn:(id)sender{

    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"User" bundle:nil];
    UIViewController *userController=[secondStroyBoard instantiateViewControllerWithIdentifier:@"CommonLoginViewController"];
    userController.view.backgroundColor = [UIColor whiteColor];
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:userController];
    
    [self presentViewController:nav animated:true completion:^(){

    }];
}

// 退出
- (IBAction)loginOut:(id)sender{
    
    [[BURequestManager sharedRequest] requestPostWithParameterWithBlockDic:[PATH_BASE stringByAppendingString:@""] SetParamer:@{@"Mobile":@"15011036823"} success:^(NSDictionary *successDic){
    
    } failure:^(NSString *errMsg){
    
    }];
}

- (void)requestDmList{
    NSDictionary *dic = @{@"pageid":@"1",@"pagesize":@"6"};
    
    [[BURequestManager sharedRequest] requestGetWithParameterWithBlockDic:@"" SetParamer:dic success:^(NSDictionary *dic){
        
        DmListModel *dmModel = [[DmListModel alloc] initWithDictionary:dic error:nil];
        NSMutableArray *arrayImg = [NSMutableArray array];
        NSMutableArray *arrayTitle = [NSMutableArray array];
        for (int i = 0; i < dmModel.data.count; i ++) {
            DmModel *model = dmModel.data[i];
            [arrayImg addObject:model.dmUrl];
            [arrayTitle addObject:model.dmName];
        }
        
        EScrollerView *scroller=[[EScrollerView alloc] initWithFrameRect:CGRectMake(0, 0, self.view.frame.size.width, 150)
                                                              ImageArray:arrayImg
                                                              TitleArray:arrayTitle];
        scroller.delegate=self;
        [headerView addSubview:scroller];
        
    } failure:^(NSString *errMsg){
        
    }];

}

- (void)scrollViewAnimation{
    NSMutableArray *dataArray1 = [NSMutableArray arrayWithCapacity:0];
    NSDictionary *bannerDic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"http://pic11.nipic.com/20101108/330698_094713037174_2.jpg", @"img_url", nil];
    [dataArray1 addObject:bannerDic1];
    bannerDic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"http://img.web07.cn/uploads/Shejituku/c100917/12TD35564P-24G8.jpg", @"img_url", nil];
    [dataArray1 addObject:bannerDic1];
    
    HMBannerView *bannerView = [[HMBannerView alloc] initWithFrame:CGRectMake(0, 0, 320, 150) scrollDirection:ScrollDirectionLandscape images:dataArray1];
    
    [bannerView setRollingDelayTime:3.0];
    [bannerView setDelegate:self];
    [bannerView setSquare:0];
    [bannerView setPageControlStyle:PageStyle_Left];
    [bannerView showClose:NO];
    
    [bannerView startDownloadImage];
    
    [headerView addSubview:bannerView];
    
}

- (void)requestTejiaList{
    
    [[BURequestManager sharedRequest] requestGetWithParameterWithBlockDic:@"" SetParamer:@{@"pageid":@"1",@"pagesize":@"6"} success:^(NSDictionary *dic){
        
        self.teJiaModel = [[TeJiaListModel alloc] initWithDictionary:dic error:nil];
        NSLog(@"self.teJiaModel %@",self.teJiaModel);
        [self._tableView reloadData];
        
    } failure:^(NSString *errMsg){
    
    }];
}


- (void)cityList:(id)sender{
    
    NSUserDefaults *standard = [NSUserDefaults standardUserDefaults];
    
    BPCityListViewController *cityList = [[BPCityListViewController alloc] init];
    
    __weak  HomeViewController *weakSelf = self;
    cityList.cityBlock = ^(CityModel *model){
        [standard setObject:[model toDictionary] forKey:@"reginInfo"];
        [standard synchronize];
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    };
    
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:cityList];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"商家";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = BACK_BAR_BUTTON_TITLE(@"沈阳", @selector(cityList:));
//    self.navigationItem.rightBarButtonItem = BAR_BUTTON_IMAGE(@"home_message", @selector(loginIn:));
    self.navigationItem.rightBarButtonItem = BAR_BUTTON_TITLE(@"登录", @selector(loginIn:));
    
    titleArray0 = @[@"发型推荐",@"美丽专题",@"附近门店",@"特价烫染"];
    titleArray1 = @[@"美发",@"美容",@"美甲",@"SPA健身"];
    // Do any additional setup after loading the view.
    [self setTableViewHeightWithTabBarhidden:NO];

    headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 245)];
    headerView.backgroundColor = [UIColor whiteColor];
    headerBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.frame.size.height - 95, self.view.frame.size.width, 95)];
    /*1.0屏蔽次view*/
    /*
    headerBtnView1 = [[UIView alloc] initWithFrame:CGRectMake(0, headerView.frame.size.height - 95, self.view.frame.size.width, 95)];
     */
    [headerView addSubview:headerBtnView];

    
    [self setHeaderBtnView:headerBtnView titleArray:titleArray0];
//    [self setHeaderBtnView:headerBtnView1 titleArray:titleArray1];

    // 请求特价列表
    [self requestTejiaList];
    // 请求DM_lIST
    [self requestDmList];
    
    [self scrollViewAnimation];
    self._tableView.tableHeaderView = headerView;
}

- (void)sectionHeaderBtnClicked:(UIGestureRecognizer *)sender{

}

- (void)setHeaderBtnView:(UIView *)headerBtnBgView titleArray:(NSArray *)titleArray{
    for (int i = 0; i  < 4; i ++) {
        
        CGFloat btnWidth = (ScreenWidth -125 )/ 4;
        CGFloat height = btnWidth;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = [UIColor clearColor];
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"home_btn%d.png",i + 1]] forState:UIControlStateNormal];
        btn.frame = CGRectMake(25 * (i + 1) + i * btnWidth, 10, btnWidth, height);
        btn.tag = 1000 + i;
        [btn addTarget:self action:@selector(headBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(25 * (i + 1) + i * btnWidth - 10, btn.frame.size.height + 15,  btnWidth + 20,20)];
        title.text = titleArray[i];
        title.backgroundColor = [UIColor clearColor];
        title.font = [UIFont systemFontOfSize:13];
        title.textAlignment = NSTextAlignmentCenter;
        title.textColor = [BPCommon colorWithHexValue:0x000000 alpha:1.0f];
        [headerBtnBgView addSubview:btn];
        [headerBtnBgView addSubview:title];
    }
}

#pragma mark -
#pragma mark HMBannerViewDelegate

- (void)imageCachedDidFinish:(HMBannerView *)bannerView
{
    if (bannerView == self.bannerView)
    {
        [self.bannerView startRolling];
    }
    else
    {
        [bannerView startRolling];
    }
}

- (void)bannerView:(HMBannerView *)bannerView didSelectImageView:(NSInteger)index withData:(NSDictionary *)bannerData
{
    
}

//
- (void)headBtnClicked:(id)sender{
    [self hideTabbar:YES];
    UIButton *btn = (UIButton *)sender;
    NSInteger tagAction = btn.tag;
    
    if (tagAction == 1000) {
        BPCategoryViewController *category =[[BPCategoryViewController alloc] init];
        [self.navigationController pushViewController:category animated:YES
         ];
    }else if (tagAction == 1001){
        BPBaseWebViewController *webView = [[BPBaseWebViewController alloc] init];
        [self.navigationController pushViewController:webView animated:YES];
    }else if (tagAction == 1002){
        StoreListViewController *category = [[StoreListViewController alloc] initWithNibName:@"StoreListViewController" bundle:nil];
        [self.navigationController pushViewController:category animated:YES];
    }else if (tagAction == 1003){
        StoreListViewController *category = [[StoreListViewController alloc] initWithNibName:@"StoreListViewController" bundle:nil];
        [self.navigationController pushViewController:category animated:YES];
    }
}


#pragma -mark
#pragma -mark UITableViewDelegate  && UITableviewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return self.teJiaModel.data.count;
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(storeList:)];
        [headerSectionView addGestureRecognizer:tap];
        return  headerSectionView;
    }
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identy = @"HomeCell";

    HomeCell  *cell = [tableView dequeueReusableCellWithIdentifier:identy];
    
    NSArray *nibs;
    if (nil == cell) {
        nibs = [[NSBundle mainBundle]loadNibNamed:@"HomeCell" owner:nil options:nil];
        cell = [nibs objectAtIndex:0];
    }

    
    if (indexPath.row %2 ==0) {
//        cell.youhui.backgroundColor = [UIColor brownColor];
        cell.youhui.text = [NSString stringWithFormat:@"%@",@"满100减20"];
    }else{
//        cell.youhui.backgroundColor = [UIColor redColor];
        cell.youhui.text = [NSString stringWithFormat:@"%@",@"满100减20"];
    }
    /*
    TeJiaModel *model = (TeJiaModel *) self.teJiaModel.data[indexPath.row];

    cell.title.text = model.productInfo;
    cell.distance.text = model.distancePrice;
    cell.saleNum.text = [NSString stringWithFormat:@"已售: %@",model.hasSale];
    [cell.imageIcon setImageWithURL:[NSURL URLWithString:model.storeImg]placeholderImage:[UIImage imageNamed:@"1.jpg"]];
    cell.distance.textColor = [BPCommon colorWithHexValue:0xfa962a alpha:1.0f];
    */
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self hideTabbar:YES];

    ProductDetailViewController *productDetail = [[ProductDetailViewController alloc] initWithNibName:@"ProductDetailViewController" bundle:nil];
    productDetail.productDetailBlock = ^(NSString *str){
        NSLog(@"%@",str);
    };
    [self.navigationController pushViewController:productDetail animated:YES];
    
}

- (void)storeList:(id)sender{

    StoreListViewController *category = [[StoreListViewController alloc] initWithNibName:@"StoreListViewController" bundle:nil];
    [self.navigationController pushViewController:category animated:YES];
}

@end
